<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
    <script src="bootstrap/js/bootstrap.js"></script>
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
</head>

<body>
<form class="form-horizontal">
    <div class="form-group">
        <label for="inputTitle" class="col-sm-2 control-label">商品标题</label>
        <div class="col-sm-10">
            <input type="text" style="width: 80%" class="form-control" id="inputTitle" placeholder="请输入商品标题">
        </div>
    </div>
    <div class="form-group">
        <label for="inputPrice" class="col-sm-2 control-label">商品价格</label>
        <div class="col-sm-10">
            <input type="text" style="width: 80%" class="form-control" id="inputPrice" placeholder="请输入商品价格">
        </div>
    </div>
    <div class="form-group">
        <label for="inputDescr" class="col-sm-2 control-label">商品描述</label>
        <div class="col-sm-10">
            <textarea cols="90" rows="10" id="inputDescr"></textarea>
        </div>
    </div>
    <div class="form-group">
        <label for="file" class="col-sm-2 control-label">商品图片</label>
        <div class="col-sm-10">
            <input type="file" style="width: 60%" class="form-control" id="file" accept="image/*">
            <button type="button" onclick="uploadImg()">上传</button>
        </div>
        <div class="col-sm-offset-2 col-sm-10" style="margin-top: 10px;">
            <img src="" id="myimg" style="width: 100px; display: none;">
            <span id="uploadStatus"></span>
        </div>
    </div>
</form>
<div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
        <button type="button" class="btn btn-primary" onclick="addGoods()">保存</button>
    </div>
</div>
</body>
</html>

<script >
    function addGoods(){
        //获取商品信息
        let title = document.getElementById('inputTitle').value;
        let inputPrice = document.getElementById('inputPrice').value;
        let inputDescr = document.getElementById('inputDescr').value;
        let img = document.getElementById('myimg').src;  // 获取上传后的图片URL
        
        // 表单验证
        if(!title || !inputPrice || !inputDescr) {
            alert('请填写商品标题、价格和描述！');
            return;
        }
        if(!img) {
            alert('请先上传商品图片！');
            return;
        }
        
        // 发送AJAX请求
        $.ajax({
            url: 'addGoods',
            type: 'POST',
            data: {
                title: title,
                price: inputPrice,
                descr: inputDescr,
                img: img,
                mid: 1  // 这里需要替换为实际的商家ID，可以从session中获取
            },
            success: function(response) {
                if(response === 'Y') {
                    alert('商品添加成功！');
                    // 清空表单
                    document.getElementById('inputTitle').value = '';
                    document.getElementById('inputPrice').value = '';
                    document.getElementById('inputDescr').value = '';
                    document.getElementById('myimg').src = '';
                    document.getElementById('myimg').style.display = 'none';
                    document.getElementById('uploadStatus').textContent = '';
                    document.getElementById('file').value = '';
                } else {
                    alert('商品添加失败！');
                }
            },
            error: function() {
                console.log(this.error)
                alert('系统错误，请稍后重试！');
            }
        });
    }
    function uploadImg(){
        const fileInput = document.getElementById('file');
        if(!fileInput.files || fileInput.files.length === 0) {
            alert('请先选择图片文件！');
            return;
        }

        const file = fileInput.files[0];
        // 验证文件类型
        if(!file.type.startsWith('image/')) {
            alert('请选择图片文件！');
            return;
        }

        document.getElementById('uploadStatus').textContent = '正在上传...';

        const client = new OSS({
            region: "oss-cn-hangzhou",
            authorizationV4: true,
            accessKeyId: "LTAI5tP28ZxLxMk9aTRWvtjC",
            accessKeySecret: "jjIHLjKTwuusSeUj8zBgQfJWCDub4x",
            bucket: "ranhan1",
        });

        // 生成唯一的文件名
        const fileName = 'goods_' + new Date().getTime() + '_' + file.name;
        
        putObject(file, fileName);
        
        async function putObject(data, fileName) {
            try {
                const options = {
                    meta: { temp: "demo" },
                    mime: data.type,
                    headers: { "Content-Type": data.type }
                };
                
                const result = await client.put(fileName, data, options);
                console.log('上传成功：', result);
                
                document.getElementById('myimg').src = result.url;
                document.getElementById('myimg').style.display = 'block';
                document.getElementById('uploadStatus').textContent = '上传成功！';
            } catch (e) {
                console.error('上传失败：', e);
                document.getElementById('uploadStatus').textContent = '上传失败，请重试！';
                alert('图片上传失败：' + e.message);
            }
        }
    }
</script>